<?php

namespace common\exception\handle;


use common\exception\base\BaseCodeException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Env;
use think\Request;
use think\Response;
use Throwable;

/**
 * @description GlobalExceptionHandle 全局异常处理
 */
class GlobalExceptionHandle extends Handle
{

    const JSON = 'json';

    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * 统一异常处理
     *
     * @access public
     * @param Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render(Request $request, Throwable $e): Response
    {
        if (Env::get('APP_DEBUG')) {
            return parent::render($request, $e)->header(config('yijiantianOA.CROSS_DOMAIN'));
        }

        $code = 500;
        $msg = $e->getMessage();

        // 验证异常
        if ($e instanceof ValidateException) {
            $code = 400;
            $msg = $e->getError();
        }

        // Http异常
        if ($e instanceof HttpException) {
            $code = $e->getStatusCode();
        }

        if ($e instanceof BaseCodeException) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }

        return Response::create(
            [
                'code' => $code,
                'msg'  => $msg,
                'data' => null
            ],
            self::JSON
        );
    }
}
